package meta

import (
	"github.com/micro-plat/hydra"
	"github.com/micro-plat/lib4go/types"
)

// AddConf 添加配置项
func AddConf(tenantID int, key, value string, vtype VType) (int64, error) {
	db := hydra.C.DB().GetRegularDB()
	params := map[string]interface{}{
		"key":       key,
		"value":     value,
		"vtype":     vtype,
		"tenant_id": tenantID,
	}
	id, _, err := db.Executes(sqlInsertConf, params)
	return id, err
}

// GetConfByKey 根据key获取配置项信息
func GetConfByKey(tenantID int, key string) (types.IXMap, error) {
	db := hydra.C.DB().GetRegularDB()
	params := map[string]interface{}{
		"key":       key,
		"tenant_id": tenantID,
	}
	data, err := db.Query(sqlGetConfByKey, params)
	if err != nil {
		return nil, err
	}
	return data.Get(0), nil
}
func GetConfs(tenantID int) (types.XMaps, error) {
	db := hydra.C.DB().GetRegularDB()
	params := map[string]interface{}{
		"tenant_id": tenantID,
	}
	data, err := db.Query(sqlGetConf, params)
	if err != nil {
		return nil, err
	}
	return data, nil
}

// GetConfByKey 获取配置项
func GetJSONConfs(tenantID int) (types.XMap, error) {
	data, err := GetConfs(tenantID)
	if err != nil {
		return nil, err
	}
	confs := types.XMaps{}
	for _, row := range data {
		conf, err := parseConf(row)
		if err != nil {
			return nil, err
		}
		confs.Append(conf)
	}
	return parseMap(confs), nil
}

// UpdateConf 根据key更新配置项信息
func UpdateConf(tenantID int, key, value string, vtype VType) error {
	db := hydra.C.DB().GetRegularDB()
	params := map[string]interface{}{
		"key":       key,
		"value":     value,
		"vtype":     vtype,
		"tenant_id": tenantID,
	}
	_, err := db.Execute(sqlUpdateConf, params)
	return err
}

// DeleteConf 根据key删除配置项
func DeleteConf(tenantID int, key string) error {
	db := hydra.C.DB().GetRegularDB()
	params := map[string]interface{}{
		"key":       key,
		"tenant_id": tenantID,
	}
	_, err := db.Execute(sqlDeleteConf, params)
	return err
}
